// Author: wsfuyibing <682805@qq.com>
// Date: 2025-06-18

package daily

import (
	"context"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/lib"
)

// Logic
// 每日场次.
type Logic struct {
	arcade   *models.Arcades
	admin    *models.ArcadeAdmins
	request  *Request
	response []*Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: make([]*Response, 0),
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Query(i, o.request); err == nil {
		o.arcade, _ = lib.Arcade.GetMaster().GetArcade(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		conditions = map[string]any{
			"arcade_id": o.arcade.Id,
			"date":      o.request.Date,
		}

		err     error
		list    []*models.TicketSession
		res     = result.New()
		service = services.NewTicketSessionService()
		tid     = make([]int64, 0)
	)

	// 1. 读取列表.
	if list, err = service.Dao.ListByMap(ctx, conditions); err != nil {
		return res.WithError(errs.ErrDatabaseQuery)
	}

	// 2. 遍历列表.
	for _, item := range list {
		// 2.1 关联鱼票.
		if item.TicketId > 0 {
			tid = append(tid, item.TicketId)
		}
		// 2.2 加入列表.
		o.response = append(o.response, (&Response{}).With(item))
	}

	// 3. 绑定鱼票.
	if len(tid) > 0 {
		if err = o.RunTicket(ctx, tid); err != nil {
			return res.WithError(err)
		}
	}

	// 4. 加载完成.
	return res.WithList(o.response)
}

// RunTicket
// 绑定鱼票.
func (o *Logic) RunTicket(ctx context.Context, tid []int64) (err error) {
	var (
		mapper map[int64]*models.Ticket
		pid    = make([]int64, 0)
	)

	// 1. 读取列表.
	if mapper, err = services.NewTicketService().MapByIdList(ctx, tid); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	// 2. 遍历场次.
	for _, v := range o.response {
		if v.TicketId > 0 {
			if u, ok := mapper[v.TicketId]; ok {
				if u.PondId > 0 {
					pid = append(pid, u.PondId)
				}
				v.WithTicket(u)
			}
		}
	}

	// 3. 关联鱼塘.
	if len(pid) > 0 {
		err = o.RunPond(ctx, pid)
	}
	return
}

// RunPond
// 绑定鱼塘.
func (o *Logic) RunPond(ctx context.Context, pid []int64) (err error) {
	var mapper map[int64]*models.ArcadePond

	if mapper, err = services.NewArcadePondService().MapByIdList(ctx, pid); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	// 2. 遍历场次.
	for _, v := range o.response {
		if v.Ticket != nil && v.Ticket.PondId > 0 {
			if u, ok := mapper[v.Ticket.PondId]; ok {
				v.Ticket.WithPond(u)
			}
		}
	}

	return
}
